home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-desktop-9.10-i386-PL.iso / casper / filesystem.squashfs / usr / share / pyshared / apt / debfile.py < prev    next >
Text File  |  2009-09-25  |  20KB  |  538 lines

  1. #  Copyright (c) 2005-2009 Canonical
  2. #
  3. #  Author: Michael Vogt <michael.vogt@ubuntu.com>
  4. #
  5. #  This program is free software; you can redistribute it and/or
  6. #  modify it under the terms of the GNU General Public License as
  7. #  published by the Free Software Foundation; either version 2 of the
  8. #  License, or (at your option) any later version.
  9. #
  10. #  This program is distributed in the hope that it will be useful,
  11. #  but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. #  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  13. #  GNU General Public License for more details.
  14. #
  15. #  You should have received a copy of the GNU General Public License
  16. #  along with this program; if not, write to the Free Software
  17. #  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
  18. #  USA
  19. """Classes for working with locally available Debian packages."""
  20. from gettext import gettext as _
  21. import os
  22. import sys
  23.  
  24. import apt_inst
  25. import apt_pkg
  26.  
  27.  
  28. # Constants for comparing the local package file with the version in the cache
  29. (VERSION_NONE, VERSION_OUTDATED, VERSION_SAME, VERSION_NEWER) = range(4)
  30.  
  31.  
  32. class NoDebArchiveException(IOError):
  33.     """Exception which is raised if a file is no Debian archive."""
  34.  
  35.  
  36. class DebPackage(object):
  37.     """A Debian Package (.deb file)."""
  38.  
  39.     _supported_data_members = ("data.tar.gz", "data.tar.bz2", "data.tar.lzma")
  40.  
  41.     debug = 0
  42.  
  43.     def __init__(self, filename=None, cache=None):
  44.         self._cache = cache
  45.         self._need_pkgs = []
  46.         self._sections = {}
  47.         self._installed_conflicts = set()
  48.         self._failure_string = ""
  49.         if filename:
  50.             self.open(filename)
  51.  
  52.     def open(self, filename):
  53.         " open given debfile "
  54.         self.filename = filename
  55.         if not apt_inst.arCheckMember(open(self.filename), "debian-binary"):
  56.             raise NoDebArchiveException(_("This is not a valid DEB archive, "
  57.                                           "missing '%s' member" %
  58.                                           "debian-binary"))
  59.         control = apt_inst.debExtractControl(open(self.filename))
  60.         self._sections = apt_pkg.ParseSection(control)
  61.         self.pkgname = self._sections["Package"]
  62.  
  63.     def __getitem__(self, key):
  64.         return self._sections[key]
  65.  
  66.     @property
  67.     def filelist(self):
  68.         """return the list of files in the deb."""
  69.         files = []
  70.  
  71.         def extract_cb(what, name, *_):
  72.             files.append(name)
  73.  
  74.         for member in self._supported_data_members:
  75.             if apt_inst.arCheckMember(open(self.filename), member):
  76.                 try:
  77.                     apt_inst.debExtract(open(self.filename), extract_cb,
  78.                                         member)
  79.                     break
  80.                 except SystemError:
  81.                     return [_("List of files for '%s' could not be read" %
  82.                               self.filename)]
  83.         return files
  84.  
  85.     def _is_or_group_satisfied(self, or_group):
  86.         """Return True if at least one dependency of the or-group is satisfied.
  87.  
  88.         This method gets an 'or_group' and analyzes if at least one dependency
  89.         of this group is already satisfied.
  90.         """
  91.         self._dbg(2, "_checkOrGroup(): %s " % (or_group))
  92.  
  93.         for dep in or_group:
  94.             depname = dep[0]
  95.             ver = dep[1]
  96.             oper = dep[2]
  97.  
  98.             # check for virtual pkgs
  99.             if not depname in self._cache:
  100.                 if self._cache.isVirtualPackage(depname):
  101.                     self._dbg(3, "_isOrGroupSatisfied(): %s is virtual dep" %
  102.                                  depname)
  103.                     for pkg in self._cache.getProvidingPackages(depname):
  104.                         if pkg.isInstalled:
  105.                             return True
  106.                 continue
  107.  
  108.             inst = self._cache[depname].installed
  109.             if inst is not None and apt_pkg.CheckDep(inst.version, oper, ver):
  110.                 return True
  111.         return False
  112.  
  113.     def _satisfy_or_group(self, or_group):
  114.         """Try to satisfy the or_group."""
  115.         for dep in or_group:
  116.             depname, ver, oper = dep
  117.  
  118.             # if we don't have it in the cache, it may be virtual
  119.             if not depname in self._cache:
  120.                 if not self._cache.isVirtualPackage(depname):
  121.                     continue
  122.                 providers = self._cache.getProvidingPackages(depname)
  123.                 # if a package just has a single virtual provider, we
  124.                 # just pick that (just like apt)
  125.                 if len(providers) != 1:
  126.                     continue
  127.                 depname = providers[0].name
  128.  
  129.             # now check if we can satisfy the deps with the candidate(s)
  130.             # in the cache
  131.             pkg = self._cache[depname]
  132.             cand = self._cache._depcache.GetCandidateVer(pkg._pkg)
  133.             if not cand:
  134.                 continue
  135.             if not apt_pkg.CheckDep(cand.VerStr, oper, ver):
  136.                 continue
  137.  
  138.             # check if we need to install it
  139.             self._dbg(2, "Need to get: %s" % depname)
  140.             self._need_pkgs.append(depname)
  141.             return True
  142.  
  143.         # if we reach this point, we failed
  144.         or_str = ""
  145.         for dep in or_group:
  146.             or_str += dep[0]
  147.             if dep != or_group[-1]:
  148.                 or_str += "|"
  149.         self._failure_string += _("Dependency is not satisfiable: %s\n" %
  150.                                  or_str)
  151.         return False
  152.  
  153.     def _check_single_pkg_conflict(self, pkgname, ver, oper):
  154.         """Return True if a pkg conflicts with a real installed/marked pkg."""
  155.         # FIXME: deal with conflicts against its own provides
  156.         #        (e.g. Provides: ftp-server, Conflicts: ftp-server)
  157.         self._dbg(3, "_checkSinglePkgConflict() pkg='%s' ver='%s' oper='%s'" %
  158.                      (pkgname, ver, oper))
  159.  
  160.         pkg = self._cache[pkgname]
  161.         if pkg.isInstalled:
  162.             pkgver = pkg.installed.version
  163.         elif pkg.markedInstall:
  164.             pkgver = pkg.candidate.version
  165.         else:
  166.             return False
  167.         #print "pkg: %s" % pkgname
  168.         #print "ver: %s" % ver
  169.         #print "pkgver: %s " % pkgver
  170.         #print "oper: %s " % oper
  171.         if (apt_pkg.CheckDep(pkgver, oper, ver) and not
  172.             self.replaces_real_pkg(pkgname, oper, ver)):
  173.             self._failure_string += _("Conflicts with the installed package "
  174.                                      "'%s'" % pkg.name)
  175.             return True
  176.         return False
  177.  
  178.     def _check_conflicts_or_group(self, or_group):
  179.         """Check the or-group for conflicts with installed pkgs."""
  180.         self._dbg(2, "_check_conflicts_or_group(): %s " % (or_group))
  181.  
  182.         or_found = False
  183.         virtual_pkg = None
  184.  
  185.         for dep in or_group:
  186.             depname = dep[0]
  187.             ver = dep[1]
  188.             oper = dep[2]
  189.  
  190.             # check conflicts with virtual pkgs
  191.             if not depname in self._cache:
  192.                 # FIXME: we have to check for virtual replaces here as
  193.                 #        well (to pass tests/gdebi-test8.deb)
  194.                 if self._cache.isVirtualPackage(depname):
  195.                     for pkg in self._cache.getProvidingPackages(depname):
  196.                         self._dbg(3, "conflicts virtual check: %s" % pkg.name)
  197.                         # P/C/R on virtal pkg, e.g. ftpd
  198.                         if self.pkgname == pkg.name:
  199.                             self._dbg(3, "conflict on self, ignoring")
  200.                             continue
  201.                         if self._check_single_pkg_conflict(pkg.name, ver,
  202.                                                            oper):
  203.                             self._installed_conflicts.add(pkg.name)
  204.                 continue
  205.             if self._check_single_pkg_conflict(depname, ver, oper):
  206.                 self._installed_conflicts.add(depname)
  207.         return bool(self._installed_conflicts)
  208.  
  209.     @property
  210.     def conflicts(self):
  211.         """List of package names conflicting with this package."""
  212.         key = "Conflicts"
  213.         try:
  214.             return apt_pkg.ParseDepends(self._sections[key])
  215.         except KeyError:
  216.             return []
  217.  
  218.     @property
  219.     def depends(self):
  220.         """List of package names on which this package depends on."""
  221.         depends = []
  222.         # find depends
  223.         for key in "Depends", "PreDepends":
  224.             try:
  225.                 depends.extend(apt_pkg.ParseDepends(self._sections[key]))
  226.             except KeyError:
  227.                 pass
  228.         return depends
  229.  
  230.     @property
  231.     def provides(self):
  232.         """List of virtual packages which are provided by this package."""
  233.         key = "Provides"
  234.         try:
  235.             return apt_pkg.ParseDepends(self._sections[key])
  236.         except KeyError:
  237.             return []
  238.  
  239.     @property
  240.     def replaces(self):
  241.         """List of packages which are replaced by this package."""
  242.         key = "Replaces"
  243.         try:
  244.             return apt_pkg.ParseDepends(self._sections[key])
  245.         except KeyError:
  246.             return []
  247.  
  248.     def replaces_real_pkg(self, pkgname, oper, ver):
  249.         """Return True if a given non-virtual package is replaced.
  250.  
  251.         Return True if the deb packages replaces a real (not virtual)
  252.         packages named (pkgname, oper, ver).
  253.         """
  254.         self._dbg(3, "replacesPkg() %s %s %s" % (pkgname, oper, ver))
  255.         pkg = self._cache[pkgname]
  256.         if pkg.isInstalled:
  257.             pkgver = pkg.installed.version
  258.         elif pkg.markedInstall:
  259.             pkgver = pkg.candidate.version
  260.         else:
  261.             pkgver = None
  262.         for or_group in self.replaces:
  263.             for (name, ver, oper) in or_group:
  264.                 if (name == pkgname and apt_pkg.CheckDep(pkgver, oper, ver)):
  265.                     self._dbg(3, "we have a replaces in our package for the "
  266.                                  "conflict against '%s'" % (pkgname))
  267.                     return True
  268.         return False
  269.  
  270.     def check_conflicts(self):
  271.         """Check if there are conflicts with existing or selected packages.
  272.  
  273.         Check if the package conflicts with a existing or to be installed
  274.         package. Return True if the pkg is OK.
  275.         """
  276.         res = True
  277.         for or_group in self.conflicts:
  278.             if self._check_conflicts_or_group(or_group):
  279.                 #print "Conflicts with a exisiting pkg!"
  280.                 #self._failure_string = "Conflicts with a exisiting pkg!"
  281.                 res = False
  282.         return res
  283.  
  284.     def compare_to_version_in_cache(self, use_installed=True):
  285.         """Compare the package to the version available in the cache.
  286.  
  287.         Checks if the package is already installed or availabe in the cache
  288.         and if so in what version, returns one of (VERSION_NONE,
  289.         VERSION_OUTDATED, VERSION_SAME, VERSION_NEWER).
  290.         """
  291.         self._dbg(3, "compareToVersionInCache")
  292.         pkgname = self._sections["Package"]
  293.         debver = self._sections["Version"]
  294.         self._dbg(1, "debver: %s" % debver)
  295.         if pkgname in self._cache:
  296.             if use_installed and self._cache[pkgname].installed:
  297.                 cachever = self._cache[pkgname].installed.version
  298.             else:
  299.                 cachever = self._cache[pkgname].candidate.version
  300.             if cachever is not None:
  301.                 cmp = apt_pkg.VersionCompare(cachever, debver)
  302.                 self._dbg(1, "CompareVersion(debver,instver): %s" % cmp)
  303.                 if cmp == 0:
  304.                     return VERSION_SAME
  305.                 elif cmp < 0:
  306.                     return VERSION_NEWER
  307.                 elif cmp > 0:
  308.                     return VERSION_OUTDATED
  309.         return VERSION_NONE
  310.  
  311.     def check(self):
  312.         """Check if the package is installable."""
  313.         self._dbg(3, "checkDepends")
  314.  
  315.         # check arch
  316.         arch = self._sections["Architecture"]
  317.         if  arch != "all" and arch != apt_pkg.Config.Find("APT::Architecture"):
  318.             self._dbg(1, "ERROR: Wrong architecture dude!")
  319.             self._failure_string = _("Wrong architecture '%s'" % arch)
  320.             return False
  321.  
  322.         # check version
  323.         if self.compare_to_version_in_cache() == VERSION_OUTDATED:
  324.             # the deb is older than the installed
  325.             self._failure_string = _("A later version is already installed")
  326.             return False
  327.  
  328.         # FIXME: this sort of error handling sux
  329.         self._failure_string = ""
  330.  
  331.         # check conflicts
  332.         if not self.check_conflicts():
  333.             return False
  334.  
  335.         # try to satisfy the dependencies
  336.         if not self._satisfy_depends(self.depends):
  337.             return False
  338.  
  339.         # check for conflicts again (this time with the packages that are
  340.         # makeed for install)
  341.         if not self.check_conflicts():
  342.             return False
  343.  
  344.         if self._cache._depcache.BrokenCount > 0:
  345.             self._failure_string = _("Failed to satisfy all dependencies "
  346.                                     "(broken cache)")
  347.             # clean the cache again
  348.             self._cache.clear()
  349.             return False
  350.         return True
  351.  
  352.     def satisfy_depends_str(self, dependsstr):
  353.         """Satisfy the dependencies in the given string."""
  354.         return self._satisfy_depends(apt_pkg.ParseDepends(dependsstr))
  355.  
  356.     def _satisfy_depends(self, depends):
  357.         """Satisfy the dependencies."""
  358.         # turn off MarkAndSweep via a action group (if available)
  359.         try:
  360.             _actiongroup = apt_pkg.GetPkgActionGroup(self._cache._depcache)
  361.         except AttributeError:
  362.             pass
  363.         # check depends
  364.         for or_group in depends:
  365.             #print "or_group: %s" % or_group
  366.             #print "or_group satified: %s" % self._is_or_group_satisfied(
  367.             #                                or_group)
  368.             if not self._is_or_group_satisfied(or_group):
  369.                 if not self._satisfy_or_group(or_group):
  370.                     return False
  371.         # now try it out in the cache
  372.         for pkg in self._need_pkgs:
  373.             try:
  374.                 self._cache[pkg].markInstall(fromUser=False)
  375.             except SystemError, e:
  376.                 self._failure_string = _("Cannot install '%s'" % pkg)
  377.                 self._cache.clear()
  378.                 return False
  379.         return True
  380.  
  381.     @property
  382.     def missing_deps(self):
  383.         """Return missing dependencies."""
  384.         self._dbg(1, "Installing: %s" % self._need_pkgs)
  385.         if self._need_pkgs is None:
  386.             self.check()
  387.         return self._need_pkgs
  388.  
  389.     @property
  390.     def required_changes(self):
  391.         """Get the changes required to satisfy the dependencies.
  392.  
  393.         Returns: a tuple with (install, remove, unauthenticated)
  394.         """
  395.         install = []
  396.         remove = []
  397.         unauthenticated = []
  398.         for pkg in self._cache:
  399.             if pkg.markedInstall or pkg.markedUpgrade:
  400.                 install.append(pkg.name)
  401.                 # check authentication, one authenticated origin is enough
  402.                 # libapt will skip non-authenticated origins then
  403.                 authenticated = False
  404.                 for origin in pkg.candidate.origins:
  405.                     authenticated |= origin.trusted
  406.                 if not authenticated:
  407.                     unauthenticated.append(pkg.name)
  408.             if pkg.markedDelete:
  409.                 remove.append(pkg.name)
  410.         return (install, remove, unauthenticated)
  411.  
  412.     def _dbg(self, level, msg):
  413.         """Write debugging output to sys.stderr."""
  414.         if level <= self.debug:
  415.             print >> sys.stderr, msg
  416.  
  417.     def install(self, install_progress=None):
  418.         """Install the package."""
  419.         if install_progress is None:
  420.             return os.system("dpkg -i %s" % self.filename)
  421.         else:
  422.             try:
  423.                 install_progress.start_update()
  424.             except AttributeError:
  425.                 install_progress.startUpdate()
  426.             res = install_progress.run(self.filename)
  427.             try:
  428.                 install_progress.finish_update()
  429.             except AttributeError:
  430.                 install_progress.finishUpdate()
  431.             return res
  432.  
  433.  
  434. class DscSrcPackage(DebPackage):
  435.     """A locally available source package."""
  436.  
  437.     def __init__(self, filename=None, cache=None):
  438.         DebPackage.__init__(self, None, cache)
  439.         self._depends = []
  440.         self._conflicts = []
  441.         self._binaries = []
  442.         if filename is not None:
  443.             self.open(filename)
  444.  
  445.     @property
  446.     def depends(self):
  447.         """Return the dependencies of the package"""
  448.         return self._depends
  449.  
  450.     @property
  451.     def conflicts(self):
  452.         """Return the dependencies of the package"""
  453.         return self._conflicts
  454.  
  455.     def open(self, file):
  456.         """Open the package."""
  457.         depends_tags = ["Build-Depends", "Build-Depends-Indep"]
  458.         conflicts_tags = ["Build-Conflicts", "Build-Conflicts-Indep"]
  459.  
  460.         fobj = open(file)
  461.         tagfile = apt_pkg.ParseTagFile(fobj)
  462.         sec = tagfile.Section
  463.         try:
  464.             while tagfile.Step() == 1:
  465.                 for tag in depends_tags:
  466.                     if not sec.has_key(tag):
  467.                         continue
  468.                     self._depends.extend(apt_pkg.ParseSrcDepends(sec[tag]))
  469.                 for tag in conflicts_tags:
  470.                     if not sec.has_key(tag):
  471.                         continue
  472.                     self._conflicts.extend(apt_pkg.ParseSrcDepends(sec[tag]))
  473.                 if sec.has_key('Source'):
  474.                     self.pkgname = sec['Source']
  475.                 if sec.has_key('Binary'):
  476.                     self.binaries = sec['Binary'].split(', ')
  477.                 if sec.has_key('Version'):
  478.                     self._sections['Version'] = sec['Version']
  479.         finally:
  480.             del sec
  481.             del tagfile
  482.             fobj.close()
  483.  
  484.         s = _("Install Build-Dependencies for "
  485.               "source package '%s' that builds %s\n") % (self.pkgname,
  486.               " ".join(self.binaries))
  487.         self._sections["Description"] = s
  488.  
  489.     def check(self):
  490.         """Check if the package is installable.."""
  491.         if not self.check_conflicts():
  492.             for pkgname in self._installed_conflicts:
  493.                 if self._cache[pkgname]._pkg.Essential:
  494.                     raise Exception(_("An essential package would be removed"))
  495.                 self._cache[pkgname].markDelete()
  496.         # FIXME: a additional run of the checkConflicts()
  497.         #        after _satisfyDepends() should probably be done
  498.         return self._satisfy_depends(self.depends)
  499.  
  500.  
  501. def _test():
  502.     """Test function"""
  503.     from apt.cache import Cache
  504.     from apt.progress import DpkgInstallProgress
  505.  
  506.     cache = Cache()
  507.  
  508.     vp = "www-browser"
  509.     #print "%s virtual: %s" % (vp, cache.isVirtualPackage(vp))
  510.     providers = cache.getProvidingPackages(vp)
  511.     print "Providers for %s :" % vp
  512.     for pkg in providers:
  513.         print " %s" % pkg.name
  514.  
  515.     d = DebPackage(sys.argv[1], cache)
  516.     print "Deb: %s" % d.pkgname
  517.     if not d.check():
  518.         print "can't be satified"
  519.         print d._failure_string
  520.     print "missing deps: %s" % d.missing_deps
  521.     print d.required_changes
  522.  
  523.     print "Installing ..."
  524.     ret = d.install(DpkgInstallProgress())
  525.     print ret
  526.  
  527.     #s = DscSrcPackage(cache, "../tests/3ddesktop_0.2.9-6.dsc")
  528.     #s.checkDep()
  529.     #print "Missing deps: ",s.missingDeps
  530.     #print "Print required changes: ", s.requiredChanges
  531.  
  532.     s = DscSrcPackage(cache=cache)
  533.     d = "libc6 (>= 2.3.2), libaio (>= 0.3.96) | libaio1 (>= 0.3.96)"
  534.     print s._satisfy_depends(apt_pkg.ParseDepends(d))
  535.  
  536. if __name__ == "__main__":
  537.     _test()
  538.